package org.huawei.dao;

import org.huawei.model.domain.User;
import org.huawei.utils.DatabaseUtil;
import org.huawei.utils.HashUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDao {

    public User login(User user) throws SQLException {
        String query = "SELECT * FROM User WHERE UserAccount = ? AND UserPassword = ?";

        // 将用户输入的密码进行 SHA-256 加密后，再去数据库中查找
        String hashedPassword = HashUtil.sha256(user.getUserPassword());

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {

            // 设置查询参数
            stmt.setString(1, user.getUserAccount());
            stmt.setString(2, hashedPassword);

            // 执行查询
            ResultSet rs = stmt.executeQuery();

            // 如果有结果，则创建用户对象并从数据库中获取数据
            if (rs.next()) {
                return mapResultSetToUser(rs);
            }
        }
        return null;
    }


    public List<User> getAllUsers() throws SQLException {
        List<User> users = new ArrayList<>();
        String query = "SELECT * FROM User";
        try (Connection conn = DatabaseUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(query)) {
            while (rs.next()) {
                User user = mapResultSetToUser(rs);
                users.add(user);
            }
        }
        return users;
    }

    private User mapResultSetToUser(ResultSet rs) throws SQLException {
        User currUser = new User();
        currUser.setUserId(rs.getInt("UserId"));
        currUser.setRoleId(rs.getInt("RoleId"));
        currUser.setUserAccount(rs.getString("UserAccount"));
        currUser.setUserPassword(rs.getString("UserPassword"));
        currUser.setUserName(rs.getString("UserName"));
        currUser.setUserEmail(rs.getString("UserEmail"));
        currUser.setUserPhone(rs.getString("UserPhone"));
        // 将数据库中的字符串转换为枚举类型
        String userStatusStr = rs.getString("UserStatus");
        User.UserStatus userStatus = User.UserStatus.valueOf(userStatusStr.toUpperCase());
        currUser.setUserStatus(userStatus);
        return currUser;
    }


    public void updateUserPassword(User currentUser) throws Exception {
        String updateQuery = "UPDATE User SET UserPassword = ? WHERE UserId = ?";

        // 使用 HashUtil 对密码进行 SHA-256 加密
        String hashedPassword = HashUtil.sha256(currentUser.getUserPassword());

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(updateQuery)) {

            // 设置 SQL 参数：第一个是加密后的密码，第二个是用户的 ID
            pstmt.setString(1, hashedPassword);
            pstmt.setInt(2, currentUser.getUserId());

            // 执行更新操作
            int affectedRows = pstmt.executeUpdate();

            if (affectedRows == 0) {
                throw new Exception("更新用户密码失败，未影响任何行。");
            }
        } catch (SQLException e) {
            throw new Exception("更新用户密码时出现错误：" + e.getMessage(), e);
        }
    }


    // 更新用户信息到数据库
    public void updateUserInDatabase(User user) throws SQLException {
        String query = "UPDATE user SET userAccount = ?, userPassword = ?, userName = ?, userEmail = ?, userPhone = ?, userStatus = ?, roleId = ? WHERE userId = ?";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {

            // 设置更新参数
            stmt.setString(1, user.getUserAccount());
            stmt.setString(2, user.getUserPassword());
            stmt.setString(3, user.getUserName());
            stmt.setString(4, user.getUserEmail());
            stmt.setString(5, user.getUserPhone());
            stmt.setString(6, user.getUserStatus().name());
            stmt.setInt(7, user.getRoleId());
            stmt.setInt(8, user.getUserId());

            // 执行更新操作
            stmt.executeUpdate();
        }
    }

    // 根据角色ID获取用户列表
    public List<User> getUsersByRoleId(int roleId) throws SQLException {
        List<User> users = new ArrayList<>();
        String query = "SELECT * FROM User WHERE RoleId = ?";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {

            stmt.setInt(1, roleId);
            ResultSet rs = stmt.executeQuery();

            // 遍历查询结果并将每个用户添加到列表中
            while (rs.next()) {
                User user = new User();
                user.setUserId(rs.getInt("UserId"));
                user.setUserName(rs.getString("Username"));
                user.setRoleId(rs.getInt("RoleId"));
                user.setUserEmail(rs.getString("UserEmail"));
                user.setUserPhone(rs.getString("UserPhone"));
                // 如果User类中有其他字段，可以继续从结果集中获取
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new SQLException("Error retrieving users for RoleId: " + roleId, e);
        }
        return users;
    }

}
